#include <stdlib.h>
#include <GL/glut.h>
#include "Trajectory.h"

Trajectory::Trajectory()
{
	Vec2 auxiliar(0.0,0.0);
	_vertices.push_back(auxiliar);

	red=0.0;
	green=0.0;
	blue=0.0;
}

void Trajectory::deleteLastVertex()
{
	if (_vertices.size()-1>0){
		_vertices.pop_back();
		_nextVertex.x=_vertices[_vertices.size()-1].x;
		_nextVertex.y=_vertices[_vertices.size()-1].y;
	}
}

void Trajectory::renderTrajectory() const
{
	glColor3f(red, green, blue);
	glLineWidth(2.0f);
	glBegin(GL_LINE_STRIP);
	for( unsigned int i = 0; i < nVertices() ; ++i)
	{
		glVertex2f( _vertices[i].x, _vertices[i].y );
	}
	glVertex2f(_nextVertex.x, _nextVertex.y); 
	glEnd();
}



void Trajectory::updateNextVertex(const Vec2& vertex)
{
	if(_vertices.back().y<vertex.y)
	_nextVertex = vertex;
}

void Trajectory::addNextVertex()
{
	// Add the vertex to the end of the vector
	if(_vertices.back().y<_nextVertex.y)
	_vertices.push_back( _nextVertex );
}

const Vec2& Trajectory::vertex(unsigned int num) const
{
	return _vertices[num];
}

unsigned int Trajectory::nVertices() const
{
	return (unsigned int)_vertices.size();
}

// Stores the Trajectory
void Trajectory::save( std::ostream& output )
{
	// Write the number of points
	output << _vertices.size() << std::endl;
	for(unsigned int i = 0; i < _vertices.size(); ++i)
	{
		output << _vertices[i].x << " " << _vertices[i].y << std::endl;
	}
}
void Trajectory::deleteRewrite()
{
	if(_vertices.size()>1)
	{
		auxiliar.x=_vertices.back().x;
		auxiliar.y=_vertices.back().y;

		deleteLastVertex();

		_vertices.push_back(auxiliar);
	}

}
// Loads a Trajectory
int Trajectory::load( std::istream& input )
{
	// Clear the previous vertices (if any)
	_vertices.clear();

	input>>trajtam;
	unsigned int total;
	input >> total;

	for(unsigned int i = 0; i < total; ++i)
	{
		float x, y;
		input >> x >> y;
		_vertices.push_back( Vec2(x, y) );
	}
	return trajtam;
}

void Trajectory::cambiarColor(float r, float g, float b)
{
	red=r;
	green=g;
	blue=b;
}

